<template>
  <div>
    <div class="main_operation">
      <div class="operation_left">
        <a-button v-if="routerShow($route,'timing_add')" type="primary" @click="addBtn">添加</a-button>
      </div>
      <div class="operation_right">
        <a-select allowClear class="mr5" style="width: 200px" v-model="formList.equipment_id" @change="val=>equipChange(val,true)" placeholder="设备名称">
          <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
        </a-select>
        <a-select allowClear v-if="formList.equipment_id" class="mr5" style="width: 160px" v-model="formList.agreement_id" placeholder="设备数据">
          <a-select-option v-for="item in itemDetail" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
        </a-select>
        <a-range-picker style="width: 220px" class="mr5"  @change="onDateChange" />
        <a-input-search style="width: 200px" v-model="formList.tasks_name" @search="val=>{formList.page = 1;changeData()}" placeholder="请输入任务名称" enterButton="查询" />
      </div>
    </div>
    <div class="main">
      <a-table :pagination="false"
        :loading="tableLoad" :columns="Fields"
        :dataSource="dataLists.data"
        :rowKey="record => record.id"
        :scroll="{x:1300, y: 500 }">
        <template v-for="(col,i) in FieldsKey" :slot="col" slot-scope="text, record, index">
          <div :key="col" :style="`color: ${dataColor[i]}`">
            <template>{{text}}</template>
          </div>
        </template>
        <template slot="status_name" slot-scope="text, record">
          <a-tag v-if="record.status" @click="imeingBtn(record,1)" color="#87d068">开启</a-tag>
          <a-tag v-else @click="imeingBtn(record,0)" color="#f50">关闭</a-tag>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button v-if="routerShow($route,'timing_update')" size="small" class="mr5" type="primary" @click="editBtn(record)">编辑</a-button>
          <a-button v-if="routerShow($route,'timing_delete')" size="small" type="danger" @click="delBtn(record)">删除</a-button>
        </template>
      </a-table>
      <div class="pageBox">
        <a-pagination :total="dataLists.total" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page"
          :defaultCurrent="1" @change="pageChange" />
      </div>
    </div>
    <!-- 添加编辑 -->
    <a-modal :maskClosable="false" :destroyOnClose="true" :title="titleModel" width="60%" v-model="visible"
      :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-form>
        <a-form-item required label="任务名称" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 12 ,xs: 24 }">
          <a-input v-model="formItem.tasks_name" style="width: 200px" placeholder="请输入任务名称" />
        </a-form-item>
        <a-form-item required label="选择功能" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 12 ,xs: 24 }">
          <a-select v-model="formItem.facility" class="mr10" style="width: 200px" placeholder="请选择功能">
            <a-select-option :value="1">向数据点发送数据</a-select-option>
            <!-- <a-select-option :value="2">向设备发送数据</a-select-option> -->
          </a-select>
        </a-form-item>
        <a-form-item required label="选择接收设备" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 12 ,xs: 24 }">
          <a-select class="mr10" style="width: 200px" v-model="formItem.equipment_id" @change="val=>equipChange(val,false)" placeholder="设备名称">
            <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
          </a-select>
          <a-select class="mr10" style="width: 200px" ref="agreement_id" v-model="formItem.agreement_id" @change="agreementChange" placeholder="设备寄存器">
            <a-select-option v-for="item in itemDetail" :value="item.id" :key="item.id" :item="item">{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="formItem.agreement_id" required label="发送数据" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 10 ,xs: 24 }">
          <a-input v-if="SendDataType" v-model="formItem.send_data"  :placeholder="SendDataTypePla" />
          <a-switch v-else checkedChildren="开" unCheckedChildren="关" @change="switchChange" v-model="sendDataSwitch" />
        </a-form-item>
        <a-form-item required label="定时器状态" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 10 ,xs: 24 }">
          <a-switch checkedChildren="开" unCheckedChildren="关" @change="timingChange" v-model="timingSwitch" />
        </a-form-item>
        <a-form-item required label="执行周期" :label-col="{ md: 5 ,xs: 24 }" :wrapper-col="{ md: 14 ,xs: 24 }">
          <a-select v-model="formItem.time_type" @change="planSecondChange" class="mr10" style="width: 100px" placeholder="周期选择">
            <a-select-option :value="1">每天</a-select-option>
            <a-select-option :value="2">N天</a-select-option>
            <a-select-option :value="3">每小时</a-select-option>
            <a-select-option :value="4">N小时</a-select-option>
            <a-select-option :value="5">N分钟</a-select-option>
            <a-select-option :value="6">每星期</a-select-option>
            <a-select-option :value="7">每月</a-select-option>
          </a-select>
          <a-input class="mr10" v-if="formItem.time_type == 2" v-model="formItem.day" type='number' :min="0" style="width: 120px" addonAfter="天" />
          <a-input class="mr10" v-if="formItem.time_type == 7" v-model="formItem.day" type='number' :min="0" style="width: 120px" addonAfter="日" />
          <a-select v-if="formItem.time_type == 6" v-model="formItem.week" class="mr10" style="width: 100px">
            <a-select-option :value="1">周一</a-select-option>
            <a-select-option :value="2">周二</a-select-option>
            <a-select-option :value="3">周三</a-select-option>
            <a-select-option :value="4">周四</a-select-option>
            <a-select-option :value="5">周五</a-select-option>
            <a-select-option :value="6">周六</a-select-option>
            <a-select-option :value="7">周日</a-select-option>
          </a-select>
          <a-input 
            v-if="formItem.time_type == 1 || formItem.time_type == 2 || formItem.time_type == 4 || formItem.time_type == 6 || formItem.time_type == 7"
             class="mr10" 
             v-model="formItem.hour" 
             type="number"
             :min="0" 
             style="width: 120px" 
             addonAfter="小时" />
          <a-input v-if="formItem.time_type == 1 || formItem.time_type == 2 || formItem.time_type == 3 || formItem.time_type == 4 || formItem.time_type == 5 || formItem.time_type == 6 || formItem.time_type == 7" class="mr10" v-model="formItem.minute" type='number' :min="0" style="width: 120px" addonAfter="分钟" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  import moment from 'moment';
  const dataColor = ["#ff1800","#c000ff","#004eff","#ff0090","#008833","#000000","#ff1800","#c000ff","#ff0090","#004eff","#ff8800","#00d2ff",]
  export default {
    name: "Monitor",
    data() {
      return {
        dataColor,
        /* 通用模块 */
        //列表
        tableLoad: false, //列表loading状态
        formList: { //列表信息
          page: 1
        },
        selectedRowKeys: [], //勾选的id
        /* 通用模块end */

        /* 添加编辑 */
        titleModel: '', //标题
        SendDataType: true,
        SendDataTypePla: '',
        sendDataSwitch: false,
        timingSwitch: false,
        visible: false, //窗口显示隐藏
        confirmLoading: false, //按钮loading状态
        checkedList: [],
        formItem: {
          tasks_name: '',
          facility: 1,
          equipment_id: undefined,
          agreement_id: undefined,
          send_data: '',
          time_type: 1,
          day: '',
          week: 1,
          hour: '',
          minute: '',
        },
        /* 添加编辑end */
      }
    },
    computed: {
      ...mapState({
        Fields: state => state.timing.Fields,
        dataLists: state => state.timing.dataLists,
        requestCode: state => state.timing.requestCode,
        equipmentData: state => state.equipment.equipmentData, //设备名称信息
        itemDetail: state => state.equiRegister.itemDetail,
      }),
      FieldsKey() {
        let FieldsKeyArr = []
        for (let i = 0; i < this.Fields.length-1; i++) {
          FieldsKeyArr.push(this.Fields[i].key)
        }
        return FieldsKeyArr
      }
    },
    mounted() {
      this.changeData()
      this.equipmentAll()
      // console.log(this.$route);
      if (this.$route.query.equipmentId != undefined) {
        this.addBtn()
        this.formItem.equipment_id = this.$route.query.equipmentId
      }
    },
    methods: {
      onDateChange(date,dateStrings) {
        console.log(date,dateStrings);
        this.formList.created_start = dateStrings[0]
        this.formList.created_end = dateStrings[1]
        this.formList.page = 1
        if (!date.length) {
          delete this.formList.created_start
          delete this.formList.created_end
        }
      },
      imeingBtn(item,val){
        console.log(item,val);
        const _this = this
        if (val) {
          this.$confirm({
            title: (
              <div>您确定<span style="color: red;">关闭</span>该定时器吗？</div>
            ),
            content: (
              <div style="color: red;">该操作有一定风险性,请仔细核对!</div>
            ),
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              _this.dataEdit({
                id: item.id,
                status: 0
              })
              _this.changeData()
            },
          });
        } else {
          this.$confirm({
            title: (
              <div>您确定<span style="color: red;">开启</span>该定时器吗？</div>
            ),
            content: (
              <div style="color: red;">该操作有一定风险性,请仔细核对!</div>
            ),
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              _this.dataEdit({
                id: item.id,
                status: 1
              })
              _this.changeData()
            },
          });
        }
      },
      switchChange(val){
        console.log(val);
        val ? this.formItem.send_data = 'FF00':this.formItem.send_data = '0000'
      },
      // 定时器开关
      timingChange(val){
        console.log(val);
        val ? this.formItem.status = 1:this.formItem.status = 0
      },
      // 选择寄存器
      agreementChange(val,option){
        // 请输入发送数据 '整数' : '浮点型
        this.formItem.send_data = ''
        this.sendDataSwitch = false
        if (option.data.attrs.item.type == 2) {
          this.formItem.send_data = '0000'
          this.SendDataType = false
        } else if(option.data.attrs.item.type == 1) {
          this.SendDataType = true
          this.SendDataTypePla = "请输入整数"
        } else if(option.data.attrs.item.type == 3) {
          this.SendDataType = true
          this.SendDataTypePla = "请输入浮点型"

        }
      },
      //设备变化
      equipChange(val,searchType) {
        searchType ? delete this.formList.agreement_id : delete this.formItem.agreement_id
        this.registerDetail(val)
      },
      ...mapActions({
       getLists: 'timing/getLists', //列表
       dataAdd: 'timing/dataAdd', //添加
       dataEdit: 'timing/dataEdit', //编辑
       dataDel: 'timing/dataDel', //删除
       equipmentAll: 'equipment/equipmentAll', //设备名称信息
       registerDetail: 'equiRegister/registerDetail', //所有设备寄存器信息
      }),
      /* 通用模块 */
      // 勾选
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys
      },
      // 重新获取列表数据
      changeData() {
        this.tableLoad = true
        setTimeout(() => {
          this.getLists(this.formList)
          this.tableLoad = false
        }, 800);
      },
      // 页码
      pageChange(page) {
        this.formList.page = page;
        this.getLists(this.formList)
      },
      /* 通用模块end */

      /* 添加编辑 */
      // 添加
      addBtn() {
        this.titleModel = '添加定时任务'
        this.formItem = {
          tasks_name: '',
          facility: 1,
          equipment_id: undefined,
          agreement_id: undefined,
          send_data: '',
          time_type: 1,
          day: '',
          week: 1,
          hour: '',
          minute: '',
          status: 0
        }
        this.timingSwitch = false
        this.visible = true
      },
      // 编辑
      editBtn(item) {
        console.log(item);
        this.titleModel = '编辑定时任务'
        this.formItem = {
          id: item.id,
          tasks_name: item.tasks_name,
          facility: Number(item.facility),
          equipment_id: item.equipment_id,
          agreement_id: item.agreement_id,
          send_data: item.send_data,
          time_type: item.time_type,
          day: item.day,
          week: Number(item.week),
          hour: item.hour,
          minute: item.minute,
          status: item.status
        }
        this.timingSwitch = item.status ? true : false
        this.visible = true
      },
      // 窗口确定
      handleOk() {
        this.confirmLoading = true;
        if (this.titleModel == '添加定时任务') {
          this.formList = { page: 1 }
          this.dataAdd(this.formItem)
        } else {
          this.dataEdit(this.formItem)
        }
        setTimeout(() => {
          if (this.requestCode === 0) {
            this.visible = false;
            this.changeData()
          }
          this.confirmLoading = false;
        }, 1000);
      },
      // 窗口取消
      handleCancel() {
        this.visible = false
      },
      /* 添加编辑end */
      /* 删除 */
      delBtn(item) {
        let _this = this
        this.$confirm({
          title: `您确定要删除 ${item.tasks_name} 吗?`,
          content: `删除后将不可恢复,请仔细核对!`,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            _this.dataDel(item.id)
            _this.changeData()
          },
        });
      },
      // 周期选择
      planSecondChange(val){
          this.formItem.day = ''
          this.formItem.week = 1
          this.formItem.hour = ''
          this.formItem.minute = ''
      }
    }
  }
</script>

<style scoped>

</style>
